package com.charles.view;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.charles.excel.CustomCellWriteHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author charles
 * @date 2022/7/5 15:43
 */
public class EasyExcelView extends MiniAbstractExcelView {

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = (String) model.get("fileName");
        fileName = URLEncoder.encode(fileName + "_" + DateUtil.format(new Date(), "yyyyMMdd"), "UTF-8");
        String sheetName = (String) model.get("sheetName");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), (Class) model.get("entity"))
                .sheet(sheetName).registerWriteHandler(new CustomCellWriteHandler()).doWrite((List) model.get("data"));
    }
}
